﻿#region License
/*
 * Copyright ©2011-2012 EasyMon Project
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *  
 */
#endregion

using System;
using System.Collections.Concurrent;
using EasyMon.Common.Clock;
using EasyMon.Common.Sources;
using EasyMon.Common.Values;

namespace EasyMon.Win.Agent.Utils
{
    public class PerfCounterStatus
    {
        protected static readonly ConcurrentDictionary<string, PerfCounterStatus> Counters = new ConcurrentDictionary<string, PerfCounterStatus>();

        private readonly object _instanceLocker = new object();

        /// <summary>
        /// Gets/sets a time when the alarm threshold was breached.
        /// </summary>
        private DateTime? _alarmBreachedAt;

        /// <summary>
        /// Gets/sets a time when the warning threshold was breached.
        /// </summary>
        private DateTime? _warningBreachedAt;

        protected PerfCounterStatus()
        {
        }

        public static PerfCounterStatus GetPerfCounterStatus(IReadOnlyPerformanceCounter counter)
        {
            return Counters.GetOrAdd(counter.FullName, k => new PerfCounterStatus());
        }

        public static void ClearPerfCounterStatuses()
        {
            Counters.Clear();    
        }

        public ValueStatus GetNewValueStatus(PerfCounterSource source, double counterValue)
        {
            lock (_instanceLocker)
            {
                var newStatus = ValueStatus.Good;

                var now = DefaultClock.CurrentTime;

                if (!double.IsNaN(source.UpperAlarmThreshold) && counterValue >= source.UpperAlarmThreshold)
                {
                    newStatus = ValidateAlarmStatus(source.TriggerIfThresholfBreachedForMilliseconds, now);
                }
                else if (!double.IsNaN(source.LowerAlarmThreshold) && counterValue <= source.LowerAlarmThreshold)
                {
                    newStatus = ValidateAlarmStatus(source.TriggerIfThresholfBreachedForMilliseconds, now);
                }
                else if (!double.IsNaN(source.UpperWarningThreshold) && counterValue >= source.UpperWarningThreshold)
                {
                    newStatus = ValidateWarningStatus(source.TriggerIfThresholfBreachedForMilliseconds, now);
                }
                else if (!double.IsNaN(source.LowerWarningThreshold) && counterValue <= source.LowerWarningThreshold)
                {
                    newStatus = ValidateWarningStatus(source.TriggerIfThresholfBreachedForMilliseconds, now);
                }
                else
                {
                    _alarmBreachedAt = null;
                    _warningBreachedAt = null;
                }

                return newStatus;
            }
        }

        private ValueStatus ValidateAlarmStatus(long triggerIfThresholfBreachedForMilliseconds, DateTime now)
        {
            var newStatus = ValidateStatus(ValueStatus.Alarm, triggerIfThresholfBreachedForMilliseconds, now, ref _alarmBreachedAt);

            if (triggerIfThresholfBreachedForMilliseconds > 0 && _warningBreachedAt == null)
                _warningBreachedAt = now;

            return newStatus;
        }

        private ValueStatus ValidateWarningStatus(long triggerIfThresholfBreachedForMilliseconds, DateTime now)
        {
            var newStatus = ValidateStatus(ValueStatus.Warning, triggerIfThresholfBreachedForMilliseconds, now, ref _warningBreachedAt);

            if (newStatus == ValueStatus.Warning && _alarmBreachedAt != null)
                _alarmBreachedAt = null;

            return newStatus;
        }

        private static ValueStatus ValidateStatus(ValueStatus expectedStatus, long triggerIfThresholfBreachedForMilliseconds, DateTime now, ref DateTime? breachedAt)
        {
            var newStatus = ValueStatus.Good;

            if (triggerIfThresholfBreachedForMilliseconds > 0)
            {
                if (breachedAt == null)
                {
                    breachedAt = now;
                }
                else if ((now - breachedAt.GetValueOrDefault()).TotalMilliseconds > triggerIfThresholfBreachedForMilliseconds)
                {
                    newStatus = expectedStatus;
                }
            }
            else
            {
                newStatus = expectedStatus;
            }

            return newStatus;
        }
    }
}
